package qotwReader.question;

import java.io.*;

import qotwReader.CmdOptions;
import qotwReader.types.EbookType;

import qotwReader.utils.*;

public class QuestionEbook
{
    final private File savedHTMLFile;
    final private QuestionData data;
    final private CmdOptions cmdOpts;
    
    public QuestionEbook(QuestionFile savedHTMLFile, QuestionData data)
    {
        this.savedHTMLFile = savedHTMLFile.getOutputFile();
        this.data = data;
        this.cmdOpts = new CmdOptions(data);
    }
    
    public void convertToFormat(EbookType outputEbook, File containsEbookConvert)
    {
        //ebook-convert input_file output_file [options]
        try
        {
            Runtime rt = Runtime.getRuntime();

            String filename = Filenames.getFilename(outputEbook, data.getFilesafeTitle(), data.getFilesafeDate());
            
            File saveFile = new File(filename);
                    //data.getFilesafeTitle() + "_" + data.getFilesafeDate() + "." + outputEbook.toString()); 
            
            if (saveFile.getParentFile() != null)
                saveFile.getParentFile().mkdirs();
            
            String cmd = 
                " ebook-convert "
                + "\"" + savedHTMLFile.getAbsoluteFile() + "\" "
                + "\"" + saveFile.getAbsoluteFile() + "\""
                + cmdOpts.getOptionsForConversion();
            
            System.out.println("cmd: " + cmd);
            
            // TODO Calibre isn't always here!
            Process cd = rt.exec(cmd, null, containsEbookConvert);//
            
            
            BufferedReader input = new BufferedReader(new InputStreamReader(cd.getInputStream()));
            
            String line = null;
            
            while((line = input.readLine()) != null)
                System.out.println(line);

            System.out.println("Exited with error code " + cd.waitFor());
    
        } catch(Exception e)
        {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
}
